use crate::models::{MappingItem, UrlMappingEnv};
use crate::result::MyResult;
use actix_web::{http::header, http::header::HeaderValue, HttpRequest};
use lazy_static::lazy_static;

pub fn target_url<T: MappingItem>(target: &T, url: &str) -> String {
    if target.replace() {
        format!("{}{}", target.target(), url.replace(&target.prefix(), ""))
    } else {
        format!("{}{}", target.target(), url)
    }
}
/*
static init: Once = Once::new();
static mut default_header1: Option<HeaderValue> = None;
pub fn get_default_header() -> &'static Option<HeaderValue> {
    unsafe {
        init.call_once(|| {
            default_header1 = HeaderValue::from_str("").ok();
        });
        &default_header1
    }
}
*/

lazy_static! {
    static ref DEFAULT_HEADER: HeaderValue = HeaderValue::from_str("").unwrap();
    static ref DEFAULT_CONTENT_TYPE: HeaderValue = HeaderValue::from_str("text/plain").unwrap();
}

pub fn get_token(req: &HttpRequest) -> MyResult<String> {
    Ok(req
        .headers()
        .get("token")
        .unwrap_or(&DEFAULT_HEADER)
        .to_str()?
        .to_string())
}
pub fn get_content_type(req: &HttpRequest) -> HeaderValue {
    req.headers()
        .get(header::CONTENT_TYPE)
        .unwrap_or_else(|| &DEFAULT_CONTENT_TYPE)
        .to_owned()
}

pub fn get_referer(req: &HttpRequest) -> HeaderValue {
    req.headers()
        .get(header::REFERER)
        .unwrap_or_else(|| &DEFAULT_HEADER)
        .to_owned()
}
